#pragma once
#include <iostream>
using namespace std;
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string>
#include <strings.h>
#include <string.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <pthread.h>

namespace Client
{
    class udpClient
    {
    public:
        udpClient(const string &ip, const uint16_t &port)
            : _sockfd(-1), _ServerIp(ip), _ServerPort(port), quit(false)
        {
        }

        // 启动套接字
        void initClient()
        {
            _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sockfd == -1)
            {
                perror("socket errno\n");
                exit(2);
            }
            cout << "socket bind success" << endl;
        }

        static void *readMessage(void *args)
        {
            int sockfd = *(static_cast<int *>(args));
            sleep(2);
            pthread_detach(pthread_self());
            while (1)
            {
                char buffer[1024];
                struct sockaddr_in temp;
                socklen_t len = sizeof(temp);
                size_t n = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (sockaddr *)&temp, &len);
                if (n >= 0)
                {
                    buffer[n] = 0;
                    cout << buffer << endl;
                }
            }
            return nullptr;
        }

        // 发送信息给服务端
        void run()
        {

            // 加入多线程
            pthread_create(&_reader, nullptr, readMessage, (void *)&_sockfd);

            // 把要发的信息封装好
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));

            server.sin_family = AF_INET;
            server.sin_port = htons(_ServerPort);
            // 将ip由点分式转换为int型，并且完成网络序列号切换
            server.sin_addr.s_addr = inet_addr(_ServerIp.c_str()); // ip

            string message;
            char buffer2[1024];
            while (!quit)
            {
                // printf("请输入#");
                // cin >> message;

                // cout << "请输入# ";
                // cerr << " # ";

                fprintf(stderr, "Enter# ");
                fflush(stderr);

                fgets(buffer2, sizeof(buffer2), stdin);
                buffer2[strlen(buffer2) - 1] = 0; // 去掉\N
                message = buffer2;
                sendto(_sockfd, message.c_str(), message.size(), 0, (sockaddr *)&server, sizeof(server));
            }
        }

        ~udpClient()
        {
        }

    private:
        int _sockfd;
        string _ServerIp;
        uint16_t _ServerPort;
        bool quit;

        pthread_t _reader;
    };
}